#include "pca.h"

unsigned int g_PCA_Capture[3] = {0};

uint16_t g_CH1_U = 0;
uint16_t g_CH1_D = 0;
uint16_t g_CH2_U = 0;
uint16_t g_CH2_D = 0;
uint16_t g_CH3_U = 0;
uint16_t g_CH3_D = 0;

void pca_init(void)
{
    CCON = 0X00;
    CMOD = 0X01;

    CL = 0;
    CH = 0;

    CCAPM0 = 0X21;
    CCAPM1 = 0X21;
    CCAPM2 = 0X21;

    CCAP0L = 0;
    CCAP0H = 0;

    CCAP1L = 0;
    CCAP1H = 0;

    CCAP2L = 0;
    CCAP2H = 0;

    g_CH1_U = 0;
    g_CH1_D = 0;
    g_CH2_U = 0;
    g_CH2_D = 0;
    g_CH3_U = 0;
    g_CH3_D = 0;

    CR = 1;
}

void PCA_Isr() interrupt 7
{
    if (CF) {
        CF = 0;
    }
    if(CCF0) {
        CCF0 = 0;
        if (CCAPM0 == 0X21) {
            CCAPM0 = 0X11;
            g_CH1_U = CCAP0H << 8 | CCAP0L;
        } else {
            CCAPM0 = 0X21;
            g_CH1_D = CCAP0H << 8 | CCAP0L;
            if (g_CH1_D >= g_CH1_U)
                g_PCA_Capture[0] = g_CH1_D - g_CH1_U;
            else
                g_PCA_Capture[0] = g_CH1_D + (0xffff - g_CH1_U);
        }
    }
    if(CCF1) {
        CCF1 = 0;
        if (CCAPM1 == 0X21) {
            CCAPM1 = 0X11;
            g_CH2_U = CCAP1H << 8 | CCAP1L;
        } else {
            CCAPM1 = 0X21;
            g_CH2_D = CCAP1H << 8 | CCAP1L;
            if (g_CH2_D >= g_CH2_U)
                g_PCA_Capture[1] = g_CH2_D - g_CH2_U;
            else
                g_PCA_Capture[1] = g_CH2_D + (0xffff - g_CH2_U);
        }
    }
    if(CCF2) {
        CCF2 = 0;
        if (CCAPM2 == 0X21) {
            CCAPM2 = 0X11;
            g_CH3_U = CCAP2H << 8 | CCAP2L;
        } else {
            CCAPM2 = 0X21;
            g_CH3_D = CCAP2H << 8 | CCAP2L;
            if (g_CH3_D >= g_CH3_U)
                g_PCA_Capture[2] = g_CH3_D - g_CH3_U;
            else
                g_PCA_Capture[2] = g_CH3_D + (0xffff - g_CH3_U);
        }
    }
}


